//
//  UserInfoViewController.m
//  carcareIOS
//
//  Created by wr on 15/11/13.
//  Copyright © 2015年 baozun. All rights reserved.
//

#import "PersonInfoViewController.h"
#import "PersonInfoButtonCell.h"
#import "PersonInfoPhotoCell.h"
#import "RefreshMgr.h"

//我的车辆列表
#import "MineCarsViewController.h"


//#import "CarInfoViewController.h"
#import "SettingsViewController.h"
#import "DeviceInfoViewController.h"
#import "MWFeedBackVC.h"
#import "MoneyTabViewController.h"
#import "UserInfoViewController.h"
#import "BaseWebViewController.h"

#import "NetAdvertice.h"
#import "AdverticePageModel.h"

//分享
#import "ShareItemView.h"
#import "ShareCenter.h"

#import "BaseWebViewController.h"

#import "WebViewHandle.h"

#define SECTION_HEIGHT (11)
#define CELL_HEIGHT (49)
//#define FOOT_VIEW_HEIGHT (50 * __MAIN_RATIO_375)

typedef NS_ENUM(NSInteger , CELL_VIEWS_TYPE) {
    CELL_LEFTLABEL_TAG = 30,//左侧icon图标
    CELL_RIGHTLabel_TAG = 10,//左侧label
    CELL_LEFTICON_IMAGEV_TAG = 40,//右侧label
    CELL_RIGHTCORNER_VIEW_TAG = 20,
};

@interface PersonInfoViewController ()

@property (nonatomic , readonly) NSArray * titleArray;

@property (nonatomic , strong) RefreshMgr *refreshMgr;

@property (nonatomic , copy) NSString * servicePhoneStr;

@property (nonatomic , assign) CGFloat footViewHeight;

@property (nonatomic , strong) PersonInfoPhotoCell * photoCell;


@property (nonatomic , copy) NSArray * dataH5Arr;


@end

@implementation PersonInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"我的";
    
    self.servicePhoneStr = @"400-034-5858";

    __weak __typeof(self) wself = self;
    
    [self navSetupRightImageName:@"Nav_Right_Setting" action:^{
        SettingsViewController * vc = [[SettingsViewController alloc] initWithTableRefreshType:TYPE_TABLE_REFRESH_NONE];
        [wself.navigationController pushViewController:[vc navSetupBackItemWithIdentification:BACK_ICON_TITLE] animated:YES];
        [UmengMgr event:ICZ_Settings];
    }];
    
    self.refreshMgr = [RefreshMgr sharedInstance];
    [self.refreshMgr.refreshDeviceStatus startRefreshWithTimeInterval:0];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateStatus) name:REFRESH_DEVICESTATUS object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateMoney) name:REFRESH_MONEY object:nil];
    [self.refreshMgr.refreshOrderNoRead startRefreshWithTimeInterval:0];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateOrderIsRead) name:REFRESH_ORDERNOREAD object:nil];
    [self createTableView];
    

}
#pragma mark - 查询订单未读
- (void)updateOrderIsRead
{
    PersonInfoPhotoCell * cell = (PersonInfoPhotoCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    cell.isShowRedCorner = (self.refreshMgr.refreshOrderNoRead.noReadOrderNum > 0);
}
-(void)updateMoney{
    
    PersonInfoPhotoCell * cell = (PersonInfoPhotoCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    cell.surplusMoneyStr = STRING_INT(self.refreshMgr.refreshMoney.currentMoney);
}
- (void)updateStatus
{
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
}
- (NSArray *)titleArray
{
    //@[@[@"推荐给朋友",@"giveMoney_Icon_Image"]]
    return @[@[@"头像"],@[@[@"我的车辆",@"myCar_Icon_Image"],@[@"我的盒子",@"equipment_Icon_Image"]],@[@"我的社区等类似广告配置"],@[@"空白"],@[@[@"意见反馈",@"opinion_Icon_Image"],@[@"联系客服",@"contact_Service_Image"]],@[@"空白"]];
}

- (void)createTableView
{
    self.tableView.frame = CGRectMake(0, 0 , __MAIN_WIDTH , __MAIN_HEIGHT_64_TABBAR );
    self.tableView.backgroundColor = [Theme backGroundColor];
    self.tableView.separatorColor = [Theme lineNewColor];
    
    self.footViewHeight = SECTION_HEIGHT ;
}

#pragma mark - tableView Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.titleArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return (section == 2 ?  (self.dataH5Arr.count > 0 ? self.dataH5Arr.count :0) : [self.titleArray[section] count]);
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    return (indexPath.section == 0 ? [PersonInfoPhotoCell getCellHeight] : ((indexPath.section == 1 ||  indexPath.section == 4) ? CELL_HEIGHT : (indexPath.section == 2 && self.dataH5Arr.count > 0) ? CELL_HEIGHT : (indexPath.section == 3 ? self.footViewHeight : SECTION_HEIGHT)));
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * cell;
    CGFloat labelX = 15 * __MAIN_RATIO_375;
    switch (indexPath.section) {
            //头像cell
        case 0:
        {
            NSString * cellID = @"photoCellID";
            cell = [tableView dequeueReusableCellWithIdentifier:cellID];
            if (!cell) {
                cell = [[PersonInfoPhotoCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
            }
            [((PersonInfoPhotoCell *)cell) reloadUserPhoto];

            self.photoCell = ((PersonInfoPhotoCell *)cell);

            __weak __typeof(self) wself = self;
            ((PersonInfoPhotoCell *)cell).photoBtnBlock = ^ (BTN_TYPE type)
            {
                switch (type) {
                        //头像按钮
                    case BTN_TYPE_ICON:
                    {
                        [UmengMgr event:ICZ_MyProfile];
                        [wself.navigationController pushViewController:[[[UserInfoViewController alloc] initWithMainViewType:TYPE_MAIN_VIEW_TABLE_NORMAL] navSetupBackItemWithIdentification:BACK_ICON_TITLE] animated:YES];
                    }
                        break;
                        //我的订单
                    case BTN_TYPE_CAR_COUNPON:
                    {
                        [UmengMgr event:ICZ_Myorder];
                        if (![Check isVisiter]) {
                            
                            NSString *url = [WebViewHandle url:[UmengMgr titleByKey:@"link_my_order"] addParams:@{@"icz_uid" : @(USERINFO.userID), @"icz_key" : USERINFO.iczkey}];
                            
                            BaseWebViewController * webVC = [[[BaseWebViewController alloc]initWithURL:url]navSetupBackItemWithIdentification:BACK_ICON];
                            [wself.navigationController pushViewController:webVC animated:YES];
                            if(wself.refreshMgr.refreshOrderNoRead.noReadOrderNum > 0)
                            {
                                [wself.refreshMgr.refreshOrderNoRead updateOrderIsReadSuccess:^(id JSON) {
                                    [wself.refreshMgr.refreshOrderNoRead startRefreshWithTimeInterval:0];
                                    wself.photoCell.isShowRedCorner = NO;

                                } failure:^(id JSON) {
                                    
                                }];
                            }
                            
                        }
                    }
                        break;
                        //剩余挣点
                    case BTN_TYPE_SURPLUS_MONEY:
                    {
                        [UmengMgr event:ICZ_Left_Point];
                        [wself.navigationController pushViewController:[[[MoneyTabViewController alloc] init] navSetupBackItemWithIdentification:BACK_ICON_TITLE] animated:YES];
                    }
                        break;
                    default:
                        break;
                }
            };
        }
            break;
            
            //我的订单 我的车辆 设备状态
            //邀请奖励 意见反馈
        case 1:
        case 2:
        case 4:
        {
            NSString * cellID = [NSString stringWithFormat:@"normallCellID%zd%zd",indexPath.section,indexPath.row];
            cell = [tableView dequeueReusableCellWithIdentifier:cellID];
            if (!cell) {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
                UIImage * iconImage = ImageNamed(@"myCar_Icon_Image");
                CGFloat imageViewY = (CELL_HEIGHT - iconImage.size.height * __MAIN_RATIO_375) / 2;
                UIImageView * iconImageV = [Factory imageViewWithFrame:CGRectMake(labelX , imageViewY, iconImage.size.width * __MAIN_RATIO_375, iconImage.size.height * __MAIN_RATIO_375) image:nil onView:cell];
                iconImageV.tag = CELL_LEFTICON_IMAGEV_TAG;
                
                UIImage * rightImage = ImageNamed(@"cell_right");
                [Factory imageViewWithCenter: CGPointMake(__MAIN_WIDTH - 25, CELL_HEIGHT / 2) image:rightImage onView:cell];
                CGFloat titleLabelX = labelX + iconImage.size.width *__MAIN_RATIO_375 + 11 * __MAIN_RATIO_375;
                CGFloat labelW = __MAIN_WIDTH - titleLabelX - (rightImage.size.width / 2 + 28);
                
                
                UIFont * leftLabelFont = FONT_TABLE_TITLE;
                NSDictionary *attributes = @{NSFontAttributeName:leftLabelFont};
                CGSize labelSize;
                if(indexPath.section != 2)labelSize = [self.titleArray[indexPath.section][indexPath.row][0] boundingRectWithSize:CGSizeMake(__MAIN_WIDTH / 3, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
                
                //左侧label
                UILabel * leftLabel = [Factory labelWithFrame:CGRectMake(titleLabelX , 0, (indexPath.section != 2 ? (labelSize.width < labelW ? labelSize.width :(labelW / 2)) : labelW) , CELL_HEIGHT) font:leftLabelFont text:@"" textColor:[Theme wordColor] onView:cell textAlignment:NSTextAlignmentLeft];
                leftLabel.tag = CELL_LEFTLABEL_TAG;
 
                //右侧label
                [Factory labelWithFrame:CGRectMake(leftLabel.origin.x + leftLabel.width , leftLabel.top, labelW - leftLabel.width + 3, leftLabel.height) font:FONT_DEFAULT_Light(13) text:@"" textColor:COLOR_RGBA(0x18, 0x18, 0x18, 0.6) onView:cell textAlignment:NSTextAlignmentRight].tag = CELL_RIGHTLabel_TAG;
                [[[UIView viewWithFrame:CGRectMake(0, CELL_HEIGHT - 0.5, __MAIN_WIDTH, 0.5)] resetBackgroundColor:[Theme lineColor]] setupOnView:cell];
            }
            
            UIImageView * leftIconImageV = (UIImageView *)[cell viewWithTag:CELL_LEFTICON_IMAGEV_TAG];
            
            UILabel * leftLabel = (UILabel *)[cell viewWithTag:CELL_LEFTLABEL_TAG];
            if(indexPath.section != 2)
            {
                [leftIconImageV setImage:ImageNamed(self.titleArray[indexPath.section][indexPath.row][1])];
                [leftLabel setText:self.titleArray[indexPath.section][indexPath.row][0]];
            }else if(self.dataH5Arr > 0){
                [leftIconImageV setImageWithURL:[NSURL URLWithString:((AdverticePageModel *)self.dataH5Arr[indexPath.row]).img]];
                [leftLabel setText:((AdverticePageModel *)self.dataH5Arr[indexPath.row]).title];
            }
            
            UILabel * rightLabel = (UILabel *)[cell viewWithTag:CELL_RIGHTLabel_TAG];
            switch (indexPath.section) {
                case 1:
                {
                    rightLabel.text = (indexPath.row == 1 ? self.refreshMgr.refreshDeviceStatus.status : (indexPath.row == 0 ? ([USERINFO.carBrand isNotNil]?USERINFO.carBrand:@"") : @""));
                }
                    break;
                default:
                    rightLabel.text = @"";
                    break;
            }
        }
            break;
            //section view cell  或 foot view cell
        case 3:
        case 5:
        {
            NSString * cellID = (indexPath.section == 5 ? @"footCellID":@"noCellID");
            cell = [tableView dequeueReusableCellWithIdentifier:cellID];
            if (!cell) {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
                UIView * backView = [[[UIView viewWithFrame:CGRectMake(0, 0, __MAIN_WIDTH, (indexPath.section == 5 ? self.footViewHeight : SECTION_HEIGHT))] resetBackgroundColor:[Theme backGroundColor]] setupOnView:cell];
                backView.layer.borderColor = (indexPath.section == 5 ? [UIColor clearColor] : [Theme lineColor]).CGColor;
                backView.layer.borderWidth = 0.5;
            }
        }
            break;
        default:
            break;
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([Check isVisiter])
    {
        return;
    }
    switch (indexPath.section) {
            //头像
        case 0:
        {
            
        }
            break;
            //我的订单 我的车辆 设备状态
        case 1:
        {
            switch (indexPath.row) {
                    //我的车辆
                case 0:
                {
                    
                    [self.navigationController pushViewController:[[[MineCarsViewController alloc] initWithTableRefreshType:TYPE_TABLE_REFRESH_PULL_DOWN] navSetupBackItemWithIdentification:BACK_ICON_TITLE] animated:YES];
                    [UmengMgr event:ICZ_CarMgrCarList];
                    [[StatisticsMgr sharedInstance] addClickID:@"我的车辆－我的车辆列表" description:[tableView cellForRowAtIndexPath:indexPath].description];
                    
                }
                    break;
                    
                    //设备状态
                case 1:
                {
                    [UmengMgr event:ICZ_MyEquipment];
                    [self.navigationController pushViewController:[[[DeviceInfoViewController alloc] initWithMainViewType:TYPE_MAIN_VIEW_NORMAL withDeviceStatus:self.refreshMgr.refreshDeviceStatus.status] navSetupBackItemWithIdentification:BACK_ICON_TITLE] animated:YES];
                }
                    break;

                default:
                    break;
            }
        }
            break;
            
        case 2://
        {
            //h5点击
            AdverticePageModel * model = self.dataH5Arr[indexPath.row];
            [[StatisticsMgr sharedInstance] addClickID:[NSString stringWithFormat:@"%@-%@",APP_PERSON_H5,model.title] description:[NSString stringWithFormat:@"我的页面中的H5设置%@",[tableView cellForRowAtIndexPath:indexPath].description]];
            [SCREEN viewController:self pushWebViewControllerWithModel:model];
        }
            break;
            
        case 4:
        {
            switch (indexPath.row) {
                    //意见反馈
                case 0:
                {
                    [UmengMgr event:ICZ_Feedback];
                    MWFeedBackVC *vc = [[[MWFeedBackVC alloc] initWithMainViewType:TYPE_MAIN_VIEW_SCROLL_NORMAL] navSetupBackItemWithIdentification:BACK_ICON_TITLE];
                    [self.navigationController pushViewController:vc animated:YES];
                }
                    break;
                    //联系客服
                case 1:
                {
                    [self.navigationController pushViewController:[[[BaseWebViewController alloc] initWithURL:@"http://r.ichezheng.com/cz/kefu/kefu.html"] navSetupBackItemWithIdentification:BACK_ICON] animated:YES];
                    [UmengMgr event:ICZ_Contact];
                }
                    break;
                default:
                    break;
            }
        }
            break;
        default:
            break;
    }
}
#pragma mark - 配置  我的社区等等页面
- (void)loadH5Data
{
    __weak __typeof(self) wself = self;
    [NetAdvertice loadAdverticesWithCode:APP_PERSON_H5 success:^(NSArray *list) {
        wself.dataH5Arr = list;
        [wself.tableView reloadData];
        wself.tableView.bounces = (__MAIN_HEIGHT == 480 ? YES : (wself.dataH5Arr.count > 1 ? YES : NO));
    } fail:^{
        
    }];
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self.refreshMgr.refreshMoney startRefreshWithTimeInterval:0];
    [self.refreshMgr.refreshDeviceStatus startRefreshWithTimeInterval:1];
    [self.refreshMgr.refreshOrderNoRead startRefreshWithTimeInterval:0];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.refreshMgr.refreshMoney stopRefresh];
    [self.refreshMgr.refreshDeviceStatus stopRefresh];
    [self.refreshMgr.refreshOrderNoRead stopRefresh];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    [self loadH5Data];
    [UmengMgr event:ICZ_Mine];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
